/**
 * SetEnvironment.java
 *
 * @author  darrell
 */

package taskmaster.util;

import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
import java.io.BufferedReader;

/**taskmaster.util.SetEnvironment
 *<BR><BR>
 * Provides a static method for setting system wide environment variables from the TMS.env file.
 *<br><br>
 *THERE MAY BE A BUG IN THE setEnvFromFile() METHOD THAT LEAVES FILE'S OPEN.
 */
public abstract class SetEnvironment {
	
	/** Creates a new instance of SetEnvironment */
	public SetEnvironment() {
		//this.setEnvFromFile();
	}
	/** sets the variables */
	public static void set() throws java.io.FileNotFoundException, Exception {
		setEnvFromFile();
	}
	
	/**Parses /omega/rc/tms.env and puts name/value pairs into System properties for use with any app.
	 * <br><br>
	 * IF RUN FROM WINDOWS (WHERE IT WAS DEVELOPED) LOOKS FOR tms.env IN PATH APPROPRIATE FOR DARRELL (L:\\darrell\\tms.env).
	 *<BR><BR>
	 *Darrell FIX 021220 - added 'FileReader fr' line, and fr.close() to fix open file handle problem.
	 */
	private static void setEnvFromFile() throws FileNotFoundException, Exception 
	{
		try {
			File f = null;
			String tmsEnvFile = null;
			if (System.getProperty("TMS_ENVFILE") != null)
				tmsEnvFile = System.getProperty("TMS_ENVFILE");
			else
				tmsEnvFile = "/omega/rc/tms.env";
			System.err.println("Using TMSENV_FILE: "+ tmsEnvFile);
			f = new File(tmsEnvFile);
			FileReader fr = new FileReader(f);
			BufferedReader br = new BufferedReader(fr);
			
			String line = null;
			StringTokenizer st = null;
			while ( (line = br.readLine()) != null ) {
				st = new StringTokenizer(line, " =");
				if (st.countTokens() == 3) {
					while (st.hasMoreTokens()) {
						st.nextToken();
						System.setProperty(st.nextToken(), st.nextToken());
					}
				}
			}
			br.close();
			fr.close();
			System.out.println("Set env vars from "+ f.toString());
		} catch (FileNotFoundException fne) {
			String expl = "taskmaster.util.SetEnvironment:setEnvFromFile: Probably could not find file that defines env vars: "+ fne;
			System.err.println(expl);
//			throw new FileNotFoundException(expl);
		} catch (Exception e) {
			String expl = "taskmaster.util.SetEnvironment:setEnvFromFile: Some exception (not FileNotFoundException): "+ e;
			System.err.println(expl);
//			throw new Exception(expl);
		}
	}
}
